import ScrollBarLayout from '@/components/ScrollBarLayout';
import { AutoComplete, Card, Col, Empty, Input, Tooltip, Tree } from 'antd';
import { ChangeEvent, useCallback, useContext, useMemo } from 'react';
import { IAuthFirstLeftTree } from '../../type';
import { AuthorizationContext } from '../AuthHooks';
import { SearchOutlined } from '@ant-design/icons';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { loopArray, loopArrayChildren } from '@/utils';

export const AuthFirstLeftTree: React.FC<IAuthFirstLeftTree> = ({
  firstMenuList,
}) => {
  const {
    prefixCls,
    leftExpandedKeys,
    leftSearchValue,
    leftSelectKeys,
    autoExpandParent,
    authGranDispatch,
  } = useContext(AuthorizationContext); //获取 上下文

  // 处理左侧树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item) => {
      const name = item?.name ?? item?.text;
      const nameLength = name?.length;
      const select = name?.search(leftSearchValue);
      const searchLength = leftSearchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = leftSearchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {item?.name ?? item?.text ?? '--'}
            </span>
          </Tooltip>
        );
      if (item?.children) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
              }}
              id={item?.id + 'left'}
            >
              <MyIcon type={item?.icon} />
              &nbsp;
              {titleTree}
            </div>
          ),
          key: item?.id,
          children: orgTreeData(item?.children),
          disabled: item?.resourceType == 0 ? true : false,
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
            id={item?.id + 'left'}
          >
            <MyIcon type={item?.icon} />
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        disabled: item?.resourceType == 0 ? true : false,
      };
    });
  };

  // 搜索下拉菜单
  const autoOptionLeft = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if ((item?.name || item?.text)?.includes(leftSearchValue)) {
          // const name = item?.name || item?.text;
          // const nameLength = name?.length;
          // const select = name?.search(leftSearchValue);
          // const searchLength = leftSearchValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = leftSearchValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(firstMenuList);
    return option;
  }, [firstMenuList, leftSearchValue]);

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key; //点击的数据的id
      const targetNode = loopArray(firstMenuList)?.find(
        (item: any) => item?.id == optionId,
      ); //平铺树
      // const rowObj = option?.itemrowobj  //点击的数据
      // let openTreeIds = transltateFn(targetNode, rowObj?.pID)  //从根节点开始选中的数据

      authGranDispatch({
        type: 'authGran-autoExpandParent',
        payload: true,
      });

      authGranDispatch({
        type: 'authGran-leftExpandedKeys',
        payload: [targetNode?.pID],
      });

      authGranDispatch({
        type: 'authGran-leftSearchValue',
        payload: value,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'left');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    authGranDispatch({
      type: 'authGran-leftSearchValue',
      payload: e.target.value,
    });
  };

  // 保存选中的值
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    let ids = [...checkedKeys?.checked, treeNodes?.node?.pID];
    let idsCopy = [...new Set(ids)];
    let handleids = handleNoChildren(idsCopy, treeNodes?.node);

    authGranDispatch({
      type: 'authGran-leftSelectKeys',
      payload: handleids,
    });

    authGranDispatch({
      type: 'authGran-leftTreeCheckRows',
      payload: handChandFather(handleids),
    });
  };

  // 处理当子节点全部没有选中时候,去除父节点选中效果
  const handleNoChildren = (idList: any[], onObj: any) => {
    let isHaveChild: any = [];
    let loopTree = (dataList: any) => {
      dataList?.forEach((item: any) => {
        if (onObj?.pID == item?.id) {
          isHaveChild = item?.children?.filter((itemChild: any) => {
            return idList?.includes(itemChild?.id);
          });
        }
      });
    };

    const firstMenu = loopArrayChildren(firstMenuList);

    loopTree(firstMenu);
    if (isHaveChild && isHaveChild?.length > 0) {
      return idList;
    } else {
      return idList?.filter((itemObj: any) => {
        return itemObj != onObj?.pID;
      });
    }
  };

  // 获取选中的值,多个子节点选中其中一个带入父节点
  const handChandFather = (checkID: any) => {
    let allTreeList = loopArrayChildren(firstMenuList);
    let checkRows = allTreeList?.filter((item: any) => {
      return checkID?.includes(item?.id);
    });
    return checkRows;
  };

  // 点击展开关闭树
  const onTreeExpand = useCallback(
    (e, a) => {
      authGranDispatch({
        type: 'authGran-leftExpandedKeys',
        payload: e,
      });
      authGranDispatch({
        type: 'authGran-autoExpandParent',
        payload: false,
      });
    },
    [leftSelectKeys],
  );

  return (
    <>
      <Col span={11} style={{ height: '100%' }}>
        <Card
          className={prefixCls + 'contentCard'}
          bordered
          title={
            <>
              <AutoComplete
                style={{ width: '100%' }}
                options={autoOptionLeft}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                onSelect={onAutoSelect}
              >
                <Input
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  placeholder="请按名称搜索"
                  allowClear={true}
                />
              </AutoComplete>
            </>
          }
        >
          <ScrollBarLayout
            style={{
              padding: '10px',
            }}
          >
            {/* <div style={{ paddingBottom: '10px' }}> */}
            {firstMenuList && firstMenuList?.length > 0 ? (
              <Tree
                treeData={orgTreeData(firstMenuList)}
                blockNode={true}
                checkable={true}
                autoExpandParent={autoExpandParent}
                onCheck={onTreeSelect}
                checkedKeys={leftSelectKeys}
                expandedKeys={leftExpandedKeys}
                onExpand={onTreeExpand}
                checkStrictly={true}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
            {/* </div> */}
          </ScrollBarLayout>
        </Card>
      </Col>
    </>
  );
};
